package afters

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
	"smart_home/api/models"
	"smart_home/api/xfyun/depots"
	"strings"
	"tools"
)

func init() {
	registerAfter("trip_intent", trip_intent)
}

func trip_intent(intent *depots.Intent, result *depots.Result) {
	var (
		to, uid, what string
		device_type   float64
		ok            bool
		err           error
		st            = beego.AppConfig.String("st")
		resmsg        = &models.ResultMsg{}
		tmSlot        *depots.TimeSlot
		dates         []string
	)

	if _, ok = intent.Data.Result[0].Data["to"]; ok {
		to = intent.Data.Result[0].Data["to"].(string)
	}

	if _, ok = intent.Data.Result[0].Data["uid"]; ok {
		uid = intent.Data.Result[0].Data["uid"].(string)
	}

	if _, ok = intent.Data.Result[0].Data["what"]; ok {
		what = intent.Data.Result[0].Data["what"].(string)
	}

	if _, ok = intent.Data.Result[0].Data["device_type"]; ok {
		device_type = intent.Data.Result[0].Data["device_type"].(float64)
	}

	tmSlot = intent.ToTimeSlot(intent.GetSlot("time").NormValue)
	dates = strings.Split(tmSlot.SuggestDatetime, "T")

	err = httplib.Post("http://api.rcenet.com/v2/trip").
		Header("st", st).
		Header("suid", uid).
		Param("what", what).
		Param("wkocc", "0000000").
		Param("to", to).
		Param("time", dates[1][0:len(dates[1])-3]).
		Param("date", dates[0]).ToJSON(resmsg)

	if err != nil {
		logs.Error(err)
		return
	}

	if resmsg.Code == 0 {
		return
	}

	result.Answer.Text = intent.Answer.Text

	// 无外放设备
	if device_type == 1 {
		if err = tools.NewJpush().
			SetAlias(uid).
			SetAlert(strings.Replace(result.Answer.Text, "好的", "已设置", 1)).
			Jump("trip").
			Send(); err != nil {
			logs.Error("notepad_get err:", err)
			return
		}
	}
}
